﻿@page "/todos"
@inject TodoContext Context

<h1>Todos</h1>

<BSForm>
    <BSInput InputType="InputType.Text" @bind-Value="@Filter" placeholder="Type to filter" />
    <BSButton Color="Color.Primary" @onclick="@onFilter">Filter</BSButton>
</BSForm>

<BSTable IsBordered="true" IsHovarable="true">
    <thead>
        <tr><th>Id</th><th>Is Done</th><th>Text</th></tr>
    </thead>
    <tbody>
        @foreach (var todo in Filtered)
        {
            var color = todo.IsDone ? Color.Success : Color.Danger;
            <BSTableRow Color="@color">
                <td><BSButton Color="Color.Secondary" @onclick="@(() => onClickItem(todo.Id))">@todo.Id</BSButton></td>
                <td>@todo.IsDone</td>
                <td>@todo.Text</td>
            </BSTableRow>
        }
    </tbody>
</BSTable>
<BSButton Color="Color.Primary" @onclick="@addNewClick">Add New</BSButton>
<h2>Selected Item</h2>
<TodoItemForm SelectedId="@SelectedId" NewTodoAdded="@NewTodoAdded" />

@functions {  
    string Filter { get; set; }
    List<TodoItem> Filtered { get; set; } = new List<TodoItem>();
    int SelectedId { get; set; } = 1;

    protected async override Task OnInitAsync()
    {
        await Context.Initialize();
        if (Context.Todos.Count == 0)
        {
            //Insert some initial data
            Context.Todos.Add(new TodoItem { IsDone = true, Text = "Create initial BlazorDB project" });
            Context.Todos.Add(new TodoItem { IsDone = true, Text = "Make a todo app" });
            Context.Todos.Add(new TodoItem { IsDone = false, Text = "Make BlazorDB really awesome!" });
            await Context.SaveChanges();
        }
        Filtered = Context.Todos.ToList<TodoItem>();
    }

    void onFilter()
    {
        if(Filter == String.Empty)
        {
            Filtered = Context.Todos.ToList<TodoItem>();
        }
        else
        {
            var query = from todo in Context.Todos
                        where todo.Text.ToLower().Contains(Filter.ToLower())
                        select todo;
            Filtered = query.ToList();
        }
    }

    void onClickItem(int i)
    {
        SelectedId = i;
        StateHasChanged();
    }

    void addNewClick()
    {
        SelectedId = 0;
        StateHasChanged();
    }

    void NewTodoAdded()
    {
        StateHasChanged();
    }
}